import pandas as pd
import folium
df = pd.read_csv('C:/Users/17858c/Documents/locationcsv.csv')
m = folium.Map(location=[35.2271, -80.8431], zoom_start=12)
for index, row in df.iterrows():
folium.Marker(
location=[row['Lat'], row['Long']],
popup=row['Litter'],
).add_to(m)
# Display the map
m
!pip install folium
Collecting folium Downloading folium-0.17.0-py2.py3-none-any.whl.metadata (3.8 kB) Collecting branca>=0.6.0 (from folium) Downloading branca-0.8.0-py3-none-any.whl.metadata (1.5 kB) Requirement already satisfied: jinja2>=2.9 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from folium) (3.1.3) Requirement already satisfied: numpy in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from folium) (1.24.3) Requirement already satisfied: requests in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from folium) (2.31.0) Collecting xyzservices (from folium) Downloading xyzservices-2024.9.0-py3-none-any.whl.metadata (4.1 kB) Requirement already satisfied: MarkupSafe>=2.0 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from jinja2>=2.9->folium) (2.1.3) Requirement already satisfied: charset-normalizer<4,>=2 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from requests->folium) (2.0.4) Requirement already satisfied: idna<4,>=2.5 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from requests->folium) (3.4) Requirement already satisfied: urllib3<3,>=1.21.1 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from requests->folium) (2.1.0) Requirement already satisfied: certifi>=2017.4.17 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from requests->folium) (2024.2.2) Downloading folium-0.17.0-py2.py3-none-any.whl (108 kB) -------------------------------------- 108.4/108.4 kB 570.8 kB/s eta 0:00:00 Downloading branca-0.8.0-py3-none-any.whl (25 kB) Downloading xyzservices-2024.9.0-py3-none-any.whl (85 kB) ---------------------------------------- 85.1/85.1 kB 4.7 MB/s eta 0:00:00 Installing collected packages: xyzservices, branca, folium Successfully installed branca-0.8.0 folium-0.17.0 xyzservices-2024.9.0
# Create a base map centered around Charlotte, NC
m = folium.Map(location=[35.2271, -80.8431], zoom_start=12)
# Define a function to return a color based on the litter amount
def get_color(Litter):
if Litter < 30:
return 'blue'
elif 10 <= Litter < 50:
return 'orange'
else:
return 'red'
# Add CircleMarkers to the map based on litter levels
for index, row in df.iterrows():
folium.CircleMarker(
location=[row['Lat'], row['Long']],
radius=5,
color=get_color(row['Litter']), # Color based on litter level
fill=True,
fill_opacity=0.7,
popup=f"Location: {row['Litter']}"
).add_to(m)
# Display the map
m
# Create a legend using HTML
legend_html = """
<div style="position: fixed;
bottom: 50px; left: 50px; width: 150px; height: 90px;
border:2px solid grey; z-index:9999; font-size:14px;
background-color:white; padding: 10px;">
<h4 style="text-align:center">Legend</h4>
<p><i class="fa fa-circle" style="color:red"></i> Red Marker</p>
<p><i class="fa fa-circle" style="color:blue"></i> Blue Marker</p>
</div>
"""
# Add the legend to the map
m.get_root().html.add_child(folium.Element(legend_html))
<branca.element.Element at 0x1f4a649e2d0>
# Create a base map centered around Charlotte, NC
m = folium.Map(location=[35.2271, -80.8431], zoom_start=12)
# Define a function to return a color based on the litter amount
def get_color(Litter):
if Litter < 30:
return 'blue'
elif 10 <= Litter < 80:
return 'orange'
else:
return 'red'
# Add CircleMarkers to the map based on litter levels
for index, row in df.iterrows():
folium.CircleMarker(
location=[row['Lat'], row['Long']],
radius=5,
color=get_color(row['Litter']), # Color based on litter level
fill=True,
fill_opacity=0.7,
popup=f"Litter Count: {row['Litter']}"
).add_to(m)
# Create a legend using HTML
legend_html = """
<div style="position: fixed;
bottom: 50px; left: 50px; width: 150px; height: 150px;
border:2px solid grey; z-index:9999; font-size:10px;
background-color:white; padding: 10px;">
<h4 style="text-align:center">Legend</h4>
<p><i class="fa fa-circle" style="color:blue"></i> Less than 30 pieces of litter</p>
<p><i class="fa fa-circle" style="color:orange"></i> Between 30 and 80 pieces of litter</p>
<p><i class="fa fa-circle" style="color:red"></i> More than 80 pieces of litter</p>
</div>
"""
m.get_root().html.add_child(folium.Element(legend_html))
# Display the map
m
!pip install geopandas
Collecting geopandas Downloading geopandas-1.0.1-py3-none-any.whl.metadata (2.2 kB) Requirement already satisfied: numpy>=1.22 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from geopandas) (1.24.3) Collecting pyogrio>=0.7.2 (from geopandas) Downloading pyogrio-0.10.0-cp311-cp311-win_amd64.whl.metadata (5.6 kB) Requirement already satisfied: packaging in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from geopandas) (23.2) Requirement already satisfied: pandas>=1.4.0 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from geopandas) (2.0.2) Collecting pyproj>=3.3.0 (from geopandas) Downloading pyproj-3.6.1-cp311-cp311-win_amd64.whl.metadata (31 kB) Collecting shapely>=2.0.0 (from geopandas) Downloading shapely-2.0.6-cp311-cp311-win_amd64.whl.metadata (7.2 kB) Requirement already satisfied: python-dateutil>=2.8.2 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from pandas>=1.4.0->geopandas) (2.8.2) Requirement already satisfied: pytz>=2020.1 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages\pytz-2022.6-py3.11.egg (from pandas>=1.4.0->geopandas) (2022.6) Collecting tzdata>=2022.1 (from pandas>=1.4.0->geopandas) Downloading tzdata-2024.2-py2.py3-none-any.whl.metadata (1.4 kB) Requirement already satisfied: certifi in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from pyogrio>=0.7.2->geopandas) (2024.2.2) Requirement already satisfied: six>=1.5 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from python-dateutil>=2.8.2->pandas>=1.4.0->geopandas) (1.16.0) Downloading geopandas-1.0.1-py3-none-any.whl (323 kB) ---------------------------------------- 323.6/323.6 kB 2.5 MB/s eta 0:00:00 Downloading pyogrio-0.10.0-cp311-cp311-win_amd64.whl (16.2 MB) ---------------------------------------- 16.2/16.2 MB 10.9 MB/s eta 0:00:00 Downloading pyproj-3.6.1-cp311-cp311-win_amd64.whl (6.1 MB) ---------------------------------------- 6.1/6.1 MB 15.5 MB/s eta 0:00:00 Downloading shapely-2.0.6-cp311-cp311-win_amd64.whl (1.4 MB) ---------------------------------------- 1.4/1.4 MB 15.2 MB/s eta 0:00:00 Downloading tzdata-2024.2-py2.py3-none-any.whl (346 kB) --------------------------------------- 346.6/346.6 kB 21.0 MB/s eta 0:00:00 Installing collected packages: tzdata, shapely, pyproj, pyogrio, geopandas Successfully installed geopandas-1.0.1 pyogrio-0.10.0 pyproj-3.6.1 shapely-2.0.6 tzdata-2024.2
import geopandas as gpd
shapefile_path = 'C:/Users/17858c/Downloads/Council_Districts/Council_Districts.shp'
gdf = gpd.read_file(shapefile_path)
folium.GeoJson(gdf).add_to(m)
<folium.features.GeoJson at 0x1f4ab168b10>
m
print(gdf)
OBJECTID District DistrictRe RepEmail \
0 1 7 Ed Driggs ed@eddriggs.com
1 2 3 Tiawana Brown Tiawana.Brown@charlottenc.gov
2 3 6 Tariq Bokhari Tariq.Bokhari@charlottenc.gov
3 4 2 Malcolm Graham Malcolm.Graham@charlottenc.gov
4 5 4 Renee Johnson Renee.Johnson@charlottenc.gov
5 6 1 Dante Anderson Dante.Anderson@charlottenc.gov
6 7 5 Marjorie Molina Marjorie.Molina@charlottenc.gov
SHAPESTAre SHAPESTLen \
0 1.149506e+09 233200.146172
1 1.899851e+09 469709.257046
2 1.063571e+09 190104.878894
3 1.365822e+09 491036.301704
4 1.218127e+09 457075.873373
5 9.324958e+08 217875.707131
6 1.114363e+09 317100.167259
geometry
0 POLYGON ((1473930.125 507326.563, 1474075 5071...
1 MULTIPOLYGON (((1407226.059 531614.548, 140754...
2 POLYGON ((1464140.538 529316.33, 1464140.5 529...
3 MULTIPOLYGON (((1405999.715 571575.958, 140601...
4 MULTIPOLYGON (((1491307.87 561883.892, 1491348...
5 POLYGON ((1464127.655 565484.496, 1464438.929 ...
6 MULTIPOLYGON (((1500913.811 561564.761, 150109...
import random
gdf.explore
m
!pip install folium matplotlib mapclassify
Requirement already satisfied: folium in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (0.17.0) Requirement already satisfied: matplotlib in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (3.6.3) Collecting mapclassify Downloading mapclassify-2.8.1-py3-none-any.whl.metadata (2.8 kB) Requirement already satisfied: branca>=0.6.0 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from folium) (0.8.0) Requirement already satisfied: jinja2>=2.9 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from folium) (3.1.3) Requirement already satisfied: numpy in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from folium) (1.24.3) Requirement already satisfied: requests in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from folium) (2.31.0) Requirement already satisfied: xyzservices in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from folium) (2024.9.0) Requirement already satisfied: contourpy>=1.0.1 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from matplotlib) (1.2.0) Requirement already satisfied: cycler>=0.10 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from matplotlib) (0.11.0) Requirement already satisfied: fonttools>=4.22.0 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from matplotlib) (4.25.0) Requirement already satisfied: kiwisolver>=1.0.1 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from matplotlib) (1.4.4) Requirement already satisfied: packaging>=20.0 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from matplotlib) (23.2) Requirement already satisfied: pillow>=6.2.0 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from matplotlib) (10.2.0) Requirement already satisfied: pyparsing>=2.2.1 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from matplotlib) (3.0.9) Requirement already satisfied: python-dateutil>=2.7 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from matplotlib) (2.8.2) Requirement already satisfied: networkx>=2.7 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from mapclassify) (3.1) Requirement already satisfied: pandas!=1.5.0,>=1.4 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from mapclassify) (2.0.2) Collecting scikit-learn>=1.0 (from mapclassify) Downloading scikit_learn-1.5.2-cp311-cp311-win_amd64.whl.metadata (13 kB) Requirement already satisfied: scipy>=1.8 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from mapclassify) (1.9.3) Requirement already satisfied: MarkupSafe>=2.0 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from jinja2>=2.9->folium) (2.1.3) Requirement already satisfied: pytz>=2020.1 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages\pytz-2022.6-py3.11.egg (from pandas!=1.5.0,>=1.4->mapclassify) (2022.6) Requirement already satisfied: tzdata>=2022.1 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from pandas!=1.5.0,>=1.4->mapclassify) (2024.2) Requirement already satisfied: six>=1.5 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from python-dateutil>=2.7->matplotlib) (1.16.0) Collecting joblib>=1.2.0 (from scikit-learn>=1.0->mapclassify) Downloading joblib-1.4.2-py3-none-any.whl.metadata (5.4 kB) Collecting threadpoolctl>=3.1.0 (from scikit-learn>=1.0->mapclassify) Downloading threadpoolctl-3.5.0-py3-none-any.whl.metadata (13 kB) Requirement already satisfied: charset-normalizer<4,>=2 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from requests->folium) (2.0.4) Requirement already satisfied: idna<4,>=2.5 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from requests->folium) (3.4) Requirement already satisfied: urllib3<3,>=1.21.1 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from requests->folium) (2.1.0) Requirement already satisfied: certifi>=2017.4.17 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from requests->folium) (2024.2.2) Downloading mapclassify-2.8.1-py3-none-any.whl (59 kB) ---------------------------------------- 59.1/59.1 kB 1.0 MB/s eta 0:00:00 Downloading scikit_learn-1.5.2-cp311-cp311-win_amd64.whl (11.0 MB) ---------------------------------------- 11.0/11.0 MB 18.7 MB/s eta 0:00:00 Downloading joblib-1.4.2-py3-none-any.whl (301 kB) ---------------------------------------- 301.8/301.8 kB 9.4 MB/s eta 0:00:00 Downloading threadpoolctl-3.5.0-py3-none-any.whl (18 kB) Installing collected packages: threadpoolctl, joblib, scikit-learn, mapclassify Successfully installed joblib-1.4.2 mapclassify-2.8.1 scikit-learn-1.5.2 threadpoolctl-3.5.0
import matplotlib
import mapclassify
import folium
import geopandas as gpd
import random # Import the random module
shapefile_path = 'C:/Users/17858c/Downloads/Council_Districts/Council_Districts.shp'
gdf = gpd.read_file(shapefile_path)
# Initialize a Folium map
m2 = folium.Map(location=[35.2271, -80.8431], zoom_start=11) # Charlotte's lat/lon
# Create a color map (a dictionary mapping each district to a color)
district_colors = {}
for idx, district in enumerate(gdf['District'].unique()):
# Assign a random color to each district
district_colors['District'] = "#%06x" % random.randint(0, 0xFFFFFF)
# Define the style function to give each district a different color
def style_function(feature):
district_name = feature['properties']['District']
return {
'fillColor': district_colors[district],
'color': 'black',
'weight': 2,
'dashArray': '5, 5',
'fillOpacity': 0.6,
}
# Add tooltips to display district names
tooltip = folium.GeoJsonTooltip(
fields=['District'], # Adjust based on your shapefile's field for district names
aliases=['District: '],
localize=True
)
# Add the GeoJSON layer to the map
geojson_layer = folium.GeoJson(
gdf,
style_function=style_function,
tooltip=tooltip,
).add_to(m2)
# Save the map to an HTML file and display
m2
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_23812\492271989.py in <cell line: 0>() 35 36 # Add the GeoJSON layer to the map ---> 37 geojson_layer = folium.GeoJson( 38 gdf, 39 style_function=style_function, ~\AppData\Local\Programs\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\Lib\site-packages\folium\features.py in __init__(self, data, style_function, highlight_function, popup_keep_highlighted, name, overlay, control, show, smooth_factor, tooltip, embed, popup, zoom_on_click, marker, **kwargs) 700 self.convert_to_feature_collection() 701 if style_function is not None: --> 702 self._validate_function(style_function, "style_function") 703 self.style_function = style_function 704 self.style_map: dict = {} ~\AppData\Local\Programs\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\Lib\site-packages\folium\features.py in _validate_function(self, func, name) 775 776 test_feature = self.data["features"][0] --> 777 if not callable(func) or not isinstance(func(test_feature), dict): 778 raise ValueError( 779 f"{name} should be a function that accepts items from " ~\AppData\Local\Temp\ipykernel_23812\492271989.py in style_function(feature) 20 district_name = feature['properties']['District'] # Adjust to the name of the field in your shapefile 21 return { ---> 22 'fillColor': district_colors[district], 23 'color': 'black', 24 'weight': 2, KeyError: '5'
import folium
import geopandas as gpd
import random # Import the random module
shapefile_path = 'C:/Users/17858c/Downloads/Council_Districts/Council_Districts.shp'
gdf = gpd.read_file(shapefile_path)
# Print the columns to check for the correct field name for the districts
print(gdf.columns)
district_column = 'District'
# Create a color map (a dictionary mapping each district to a unique color)
district_colors = {}
for idx, district in enumerate(gdf[district_column].unique()): # Using the correct column here
# Assign a random color to each district
district_colors[str(district)] = "#%06x" % random.randint(0, 0xFFFFFF) # Convert district to string
# Define the style function to give each district a different color
def style_function(feature):
district_name = str(feature['properties'][district_column]) # Convert to string in case it's a number
return {
'fillColor': district_colors[District], # Now using the correct key
'color': 'black',
'weight': 2,
'dashArray': '5, 5',
'fillOpacity': 0.6,
}
# Add tooltips to display district names
tooltip = folium.GeoJsonTooltip(
fields=[district_column], # Adjust based on your shapefile's field for district names
aliases=['District: '],
localize=True
)
# Add the GeoJSON layer to the map
geojson_layer = folium.GeoJson(
gdf,
style_function=style_function,
tooltip=tooltip,
).add_to(m)
# Save the map to an HTML file and display
m
Index(['OBJECTID', 'District', 'DistrictRe', 'RepEmail', 'SHAPESTAre',
'SHAPESTLen', 'geometry'],
dtype='object')
--------------------------------------------------------------------------- NameError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_23812\3984684925.py in <cell line: 0>() 39 40 # Add the GeoJSON layer to the map ---> 41 geojson_layer = folium.GeoJson( 42 gdf, 43 style_function=style_function, ~\AppData\Local\Programs\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\Lib\site-packages\folium\features.py in __init__(self, data, style_function, highlight_function, popup_keep_highlighted, name, overlay, control, show, smooth_factor, tooltip, embed, popup, zoom_on_click, marker, **kwargs) 700 self.convert_to_feature_collection() 701 if style_function is not None: --> 702 self._validate_function(style_function, "style_function") 703 self.style_function = style_function 704 self.style_map: dict = {} ~\AppData\Local\Programs\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\Lib\site-packages\folium\features.py in _validate_function(self, func, name) 775 776 test_feature = self.data["features"][0] --> 777 if not callable(func) or not isinstance(func(test_feature), dict): 778 raise ValueError( 779 f"{name} should be a function that accepts items from " ~\AppData\Local\Temp\ipykernel_23812\3984684925.py in style_function(feature) 24 district_name = str(feature['properties'][district_column]) # Convert to string in case it's a number 25 return { ---> 26 'fillColor': district_colors[District], # Now using the correct key 27 'color': 'black', 28 'weight': 2, NameError: name 'District' is not defined
import geopandas as gpd
import matplotlib.pyplot as plt
# Plotting the GeoDataFrame
fig, ax = plt.subplots(figsize=(10, 10))
# Assign each district its own color using the 'column' parameter
gdf.plot(column='District', ax=ax, legend=True, cmap='Set3')
# Display the plot
gdf.explore()
pip install branca
Requirement already satisfied: branca in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (0.8.0) Requirement already satisfied: jinja2>=3 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from branca) (3.1.3) Requirement already satisfied: MarkupSafe>=2.0 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from jinja2>=3->branca) (2.1.3) Note: you may need to restart the kernel to use updated packages.
import geopandas as gpd
import folium
import branca
# Get the center of your GeoDataFrame for initializing the map
center = [gdf.geometry.centroid.y.mean(), gdf.geometry.centroid.x.mean()]
# Initialize the Folium map
m3 = folium.Map(location=center, zoom_start=12)
# Create a colormap using branca
colormap = branca.colormap.linear.Set3_08.scale(gdf['District'].min(), gdf['District'].max())
# Function to add each district with a different color
folium.GeoJson(
gdf,
style_function=lambda feature: {
'fillColor': colormap(feature['District']),
'color': 'black',
'weight': 1.5,
'fillOpacity': 0.6
},
tooltip=folium.GeoJsonTooltip(fields=['District'])
).add_to(m3)
# Display the map
m3
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_23812\1593806253.py in <cell line: 0>() 10 11 # Create a colormap using branca ---> 12 colormap = branca.colormap.linear.Set3_08.scale(gdf['District'].min(), gdf['District'].max()) 13 14 # Function to add each district with a different color ~\AppData\Local\Programs\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\Lib\site-packages\branca\colormap.py in scale(self, vmin, vmax, max_labels) 478 return LinearColormap( 479 self.colors, --> 480 index=[ 481 vmin + (vmax - vmin) * (x - self.vmin) * 1.0 / (self.vmax - self.vmin) 482 for x in self.index ~\AppData\Local\Programs\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\Lib\site-packages\branca\colormap.py in <listcomp>(.0) 479 self.colors, 480 index=[ --> 481 vmin + (vmax - vmin) * (x - self.vmin) * 1.0 / (self.vmax - self.vmin) 482 for x in self.index 483 ], # noqa TypeError: unsupported operand type(s) for -: 'str' and 'str'
gdf.columns
Index(['OBJECTID', 'District', 'DistrictRe', 'RepEmail', 'SHAPESTAre',
'SHAPESTLen', 'geometry'],
dtype='object')
pip install pandas
Requirement already satisfied: pandas in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (2.0.2) Requirement already satisfied: python-dateutil>=2.8.2 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from pandas) (2.8.2) Requirement already satisfied: pytz>=2020.1 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages\pytz-2022.6-py3.11.egg (from pandas) (2022.6) Requirement already satisfied: tzdata>=2022.1 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from pandas) (2024.2) Requirement already satisfied: numpy>=1.21.0 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from pandas) (1.24.3) Requirement already satisfied: six>=1.5 in c:\users\17858c\appdata\local\programs\arcgis\pro\bin\python\envs\arcgispro-py3\lib\site-packages (from python-dateutil>=2.8.2->pandas) (1.16.0) Note: you may need to restart the kernel to use updated packages.
import pandas as pd
df.plot()
<AxesSubplot: >
pip install geopy
Collecting geopy Downloading geopy-2.4.1-py3-none-any.whl.metadata (6.8 kB) Collecting geographiclib<3,>=1.52 (from geopy) Downloading geographiclib-2.0-py3-none-any.whl.metadata (1.4 kB) Downloading geopy-2.4.1-py3-none-any.whl (125 kB) -------------------------------------- 125.4/125.4 kB 669.8 kB/s eta 0:00:00 Downloading geographiclib-2.0-py3-none-any.whl (40 kB) ---------------------------------------- 40.3/40.3 kB 1.9 MB/s eta 0:00:00 Installing collected packages: geographiclib, geopy Successfully installed geographiclib-2.0 geopy-2.4.1 Note: you may need to restart the kernel to use updated packages.
import pandas as pd
import folium
# Initialize a map centered at the mean of all locations
center_lat = df['Lat'].mean()
center_lon = df['Long'].mean()
map_plot = folium.Map(location=[center_lat, center_lon], zoom_start=12)
# Add markers to the map for each address
for index, row in df.iterrows():
folium.CircleMarker(
location=[row['Lat'], row['Long']],
radius=row['Litter'] / 10, # Scale the radius by litter amount
popup=f"{row['Address']} - Litter: {row['Litter']}",
color='blue',
fill=True,
fill_color='blue'
).add_to(map_plot)
# To display the map in Jupyter directly
map_plot
# Convert the GeoDataFrame to GeoJSON format so folium can use it
geojson_data = gdf.to_crs(epsg=4326).to_json() # Make sure the CRS is in WGS84 (EPSG:4326)
# Initialize the map, centered at the mean latitude and longitude
center_lat = df['Lat'].mean()
center_lon = df['Long'].mean()
map_plot = folium.Map(location=[center_lat, center_lon], zoom_start=12)
#Add the shapefile as an overlay using GeoJSON
folium.GeoJson(
geojson_data,
name='Council Districts',
style_function=lambda feature: {
'fillColor': 'orange',
'color': 'black',
'weight': 2,
'fillOpacity': 0.2,
}
).add_to(map_plot)
#Plot the points for each address
for index, row in df.iterrows():
folium.CircleMarker(
location=[row['Lat'], row['Long']],
radius=row['Litter'] / 10, # Adjust the size based on the litter amount
popup=f"{row['Address']} - Litter: {row['Litter']}",
color='blue',
fill=True,
fill_color='blue'
).add_to(map_plot)
Add layer control to switch between council districts and markers
folium.LayerControl().add_to(map_plot)
map_plot
import matplotlib.colors as mcolors
unique_districts = gdf['District'].unique()
colors = list(mcolors.TABLEAU_COLORS.values()) # Get a predefined color palette
district_colors = {district: colors[i % len(colors)] for i, district in enumerate(unique_districts)}
# Step 5: Initialize the map, centered at the mean latitude and longitude
center_lat = df['Lat'].mean()
center_lon = df['Long'].mean()
map_plot = folium.Map(location=[center_lat, center_lon], zoom_start=12)
# Step 6: Add the shapefile with different colors for each district
def style_function(feature):
district_id = feature['properties']['District']
return {
'fillColor': district_colors[district_id],
'color': 'black',
'weight': 2,
'fillOpacity': 0.4,
}
folium.GeoJson(
geojson_data,
name='Council Districts',
style_function=style_function
).add_to(map_plot)
# Step 7: Plot the points for each address
for index, row in df.iterrows():
folium.CircleMarker(
location=[row['Lat'], row['Long']],
radius=row['Litter'] / 10, # Adjust the size based on the litter amount
popup=f"{row['Address']} - Litter: {row['Litter']}",
color='blue',
fill=True,
fill_color='blue'
).add_to(map_plot)
# Step 8: Add layer control to switch between council districts and markers
folium.LayerControl().add_to(map_plot)
# To display the map directly in Jupyter Notebook:
map_plot
gdf.columns
Index(['OBJECTID', 'District', 'DistrictRe', 'RepEmail', 'SHAPESTAre',
'SHAPESTLen', 'geometry'],
dtype='object')
unique_districts = gdf['District'].unique()
colors = list(mcolors.TABLEAU_COLORS.values()) # Get a predefined color palette
district_colors = {district: colors[i % len(colors)] for i, district in enumerate(unique_districts)}
#Initialize the map, centered at the mean latitude and longitude
center_lat = df['Lat'].mean()
center_lon = df['Long'].mean()
map_plot = folium.Map(location=[center_lat, center_lon], zoom_start=12)
#Add the shapefile with different colors for each district
def style_function(feature):
district_id = feature['properties']['District']
return {
'fillColor': district_colors[district_id],
'color': 'black',
'weight': 2,
'fillOpacity': 0.4,
}
folium.GeoJson(
geojson_data,
name='Council Districts',
style_function=style_function
).add_to(map_plot)
#Plot the points for each address
for index, row in df.iterrows():
folium.CircleMarker(
location=[row['Lat'], row['Long']],
radius=3,
popup=f"{row['Address']} - Litter: {row['Litter']}",
color='blue',
fill=True,
fill_color='blue'
).add_to(map_plot)
folium.LayerControl().add_to(map_plot)
map_plot
from matplotlib import cm
unique_districts = gdf['District'].unique()
colors = list(mcolors.TABLEAU_COLORS.values()) # Predefined color palette
district_colors = {district: colors[i % len(colors)] for i, district in enumerate(unique_districts)}
# Step 5: Initialize the map
center_lat = df['Lat'].mean()
center_lon = df['Long'].mean()
map_plot = folium.Map(location=[center_lat, center_lon], zoom_start=12)
# Step 6: Add the shapefile with different colors for each district
def style_function(feature):
district_id = feature['properties']['District'] # Use correct column name from shapefile
return {
'fillColor': district_colors[district_id],
'color': 'black',
'weight': 2,
'fillOpacity': 0.4,
}
folium.GeoJson(
geojson_data,
name='Council Districts',
style_function=style_function
).add_to(map_plot)
def get_color_for_litter_amount(litter_amount):
if litter_amount <= 30:
return 'blue' # Low range
elif 11 <= litter_amount <= 80:
return 'yellow' # Medium range
elif litter_amount > 80:
return 'red' # High range
else:
return 'gray' # Fallback color for unexpected values
# Step 8: Plot the points for each address with color-coded litter amounts based on the defined ranges
for index, row in df.iterrows():
litter_amount = row['Litter']
# Get the color based on the litter amount using the custom function
color = get_color_for_litter_amount(litter_amount)
folium.CircleMarker(
location=[row['Lat'], row['Long']],
radius=5, # Set a constant radius for all markers
popup=f"{row['Address']} - Litter Amount: {row['Litter']}",
color=color, # Use the color based on the litter amount range
fill=True,
fill_color=color
).add_to(map_plot)
folium.LayerControl().add_to(map_plot)
legend_html = f"""
<div style="position: fixed;
bottom: 50px; left: 50px; width: 300px; height: auto;
border:2px solid grey; z-index:9999; font-size:14px;
background-color:white;
padding: 10px;
">
<h4 style="margin-top: 5px">Litter Amount & Council Districts</h4>
<div style="display: flex; justify-content: space-between;">
<div style="flex: 1; padding-right: 10px;">
<b>Litter Amount</b><br>
<i style="background:blue; width:20px; height:20px; display:inline-block;"></i> Low (<= 30)<br>
<i style="background:yellow; width:20px; height:20px; display:inline-block;"></i> Medium (11 - 80)<br>
<i style="background:red; width:20px; height:20px; display:inline-block;"></i> High (> 80)<br>
</div>
<div style="flex: 1;">
<b>Council Districts</b><br>
{''.join([f'<i style="background:{district_colors[district]}; width:20px; height:20px; display:inline-block;"></i> {district}<br>' for district in unique_districts])}
</div>
</div>
</div>
"""
# Add the legend to the map
map_plot.get_root().html.add_child(folium.Element(legend_html))
map_plot.save('litter_map_with_sorted_legend.html')
# To display in Jupyter:
map_plot
map_plot.save('litter_map_with_sorted_legend.html')